package com.jianan.mis.app.overseastudy;

import static com.jianan.mis.util.ui.calendar.SWTCalendarWrapper.openCalendar;

import java.math.BigDecimal;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.List;

import org.apache.commons.lang.ArrayUtils;
import org.apache.commons.lang.math.NumberUtils;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.dialogs.IDialogConstants;
import org.eclipse.jface.dialogs.MessageDialog;
import org.eclipse.swt.SWT;
import org.eclipse.swt.events.MouseAdapter;
import org.eclipse.swt.events.MouseEvent;
import org.eclipse.swt.events.SelectionAdapter;
import org.eclipse.swt.events.SelectionEvent;
import org.eclipse.swt.graphics.Point;
import org.eclipse.swt.layout.GridData;
import org.eclipse.swt.layout.GridLayout;
import org.eclipse.swt.widgets.Button;
import org.eclipse.swt.widgets.Combo;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Control;
import org.eclipse.swt.widgets.Label;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.swt.widgets.Text;

import com.jianan.mis.data.cache.CountryCache;
import com.jianan.mis.data.domain.Country;
import com.jianan.mis.data.domain.Department;
import com.jianan.mis.data.domain.OsDepartmentContract;
import com.jianan.mis.service.DepartmentService;
import com.jianan.mis.service.OsContractService;
import com.jianan.mis.service.OsDepartmentContractService;
import com.jianan.mis.sys.IMessageKeys;
import com.jianan.mis.sys.SpringBeanFactory;
import com.jianan.mis.util.StringUtils;

public class OsDepartmentContractDialog extends Dialog {

	private Button checkLicense;
	private Text txtRemainingDeposit;
	private Combo comboCountry;
	private Text txtStudentName;
	private Combo comboDepartment;
	private Text txtContractNo;
	private Text txtSignupSum;
	private Text txtSignupDate;
	final private SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy年MM月dd日");
	/**
	 * Create the dialog
	 * @param parentShell
	 */
	public OsDepartmentContractDialog(Shell parentShell) {
		super(parentShell);
	}

	/**
	 * Create contents of the dialog
	 * @param parent
	 */
	@Override
	protected Control createDialogArea(Composite parent) {
		Composite container = (Composite) super.createDialogArea(parent);
		final GridLayout gridLayout = new GridLayout();
		gridLayout.numColumns = 2;
		gridLayout.marginTop = 20;
		gridLayout.marginLeft = 20;
		container.setLayout(gridLayout);

		final Label label = new Label(container, SWT.NONE);
		label.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label.setText("签约日期:");

		txtSignupDate = new Text(container, SWT.BORDER);
		txtSignupDate.addMouseListener(new MouseAdapter() {
			public void mouseDown(final MouseEvent e) {
				openCalendar(e, txtSignupDate, dateFormat);
			}
		});
		txtSignupDate.setEditable(false);
		final GridData gd_txtSignupDate = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtSignupDate.widthHint = 90;
		txtSignupDate.setLayoutData(gd_txtSignupDate);

		final Label label_1 = new Label(container, SWT.NONE);
		label_1.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_1.setText("签约金额:");

		txtSignupSum = new Text(container, SWT.BORDER);
		final GridData gd_txtSignupSum = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtSignupSum.widthHint = 100;
		txtSignupSum.setLayoutData(gd_txtSignupSum);

		final Label label_2 = new Label(container, SWT.NONE);
		label_2.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_2.setText("合同号:");

		txtContractNo = new Text(container, SWT.BORDER);
		final GridData gd_txtContractNo = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtContractNo.widthHint = 150;
		txtContractNo.setLayoutData(gd_txtContractNo);

		final Label label_3 = new Label(container, SWT.NONE);
		label_3.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_3.setText("部门:");

		comboDepartment = new Combo(container, SWT.READ_ONLY);
		comboDepartment.addSelectionListener(new SelectionAdapter() {
			public void widgetSelected(final SelectionEvent e) {
				txtRemainingDeposit.setText(departmentService.getRemainingDeposit(
						departmentIds.get(comboDepartment.getSelectionIndex())).toString());
			}
		});
		final GridData gd_comboDepartment = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboDepartment.setLayoutData(gd_comboDepartment);

		final Label label_4 = new Label(container, SWT.NONE);
		label_4.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_4.setText("学生姓名:");

		txtStudentName = new Text(container, SWT.BORDER);
		final GridData gd_txtStudentName = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtStudentName.widthHint = 80;
		txtStudentName.setLayoutData(gd_txtStudentName);

		final Label label_5 = new Label(container, SWT.NONE);
		label_5.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_5.setText("签约国家:");

		comboCountry = new Combo(container, SWT.READ_ONLY);
		final GridData gd_comboCountry = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		comboCountry.setLayoutData(gd_comboCountry);

		final Label label_6 = new Label(container, SWT.NONE);
		label_6.setLayoutData(new GridData(SWT.RIGHT, SWT.CENTER, false, false));
		label_6.setText("押金剩余额度:");

		txtRemainingDeposit = new Text(container, SWT.BORDER);
		txtRemainingDeposit.setEditable(false);
		final GridData gd_txtRemainingDeposit = new GridData(SWT.LEFT, SWT.CENTER, true, false);
		gd_txtRemainingDeposit.widthHint = 100;
		txtRemainingDeposit.setLayoutData(gd_txtRemainingDeposit);
		new Label(container, SWT.NONE);

		checkLicense = new Button(container, SWT.CHECK);
		checkLicense.setText("特许");
		
		setupValues();
		
		if (readonly) {
			container.setEnabled(false);
		} else {
			container.setEnabled(true);
		}
		
		if (osDepartmentContract != null) {
			txtSignupDate.setText(dateFormat.format(osDepartmentContract.getSignupDate()));
			txtSignupSum.setText(osDepartmentContract.getSignupSum().toString());
			txtContractNo.setText(osDepartmentContract.getContractNo());
			comboDepartment.select(ArrayUtils.indexOf(departmentIds.toArray(), osDepartmentContract.getDepartment().getId()));
			txtStudentName.setText(osDepartmentContract.getName());
			comboCountry.select(ArrayUtils.indexOf(countryIds.toArray(), osDepartmentContract.getCountry().getId()));
			checkLicense.setSelection(osDepartmentContract.isLicense());
			txtRemainingDeposit.setText(departmentService.getRemainingDeposit(osDepartmentContract.getDepartment().getId()).toString());
		}
		
		//
		return container;
	}
	
	private boolean readonly;
	
	private OsDepartmentContract osDepartmentContract;
	
	public void setReadonly(boolean readonly) {
		this.readonly = readonly;
	}

	private DepartmentService departmentService = (DepartmentService) SpringBeanFactory
			.getBean("departmentService");

	private OsDepartmentContractService osDepartmentContractService = (OsDepartmentContractService) SpringBeanFactory
			.getBean("osDepartmentContractService");

	private OsContractService osContractService = (OsContractService) SpringBeanFactory
			.getBean("osContractService");
	
	List<Integer> countryIds = new ArrayList<Integer>();
	List<Integer> departmentIds = new ArrayList<Integer>();
	
	private void setupValues() {
		List<Country> countries = CountryCache.getInstance().getAllCountries();
		if (countries != null) {
			for (Country country : countries) {
				countryIds.add(country.getId());
				comboCountry.add(country.getName());
			}
		}
		List<Department> departments = departmentService.getAll();
		if (departments != null) {
			for (Department department : departments) {
				departmentIds.add(department.getId());
				comboDepartment.add(department.getName());
			}
		}
	}
	
	private boolean checkInfo() {
		if (StringUtils.isEmpty(txtSignupDate.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入签约日期!");
			txtSignupDate.setFocus();
			return false;
		}
		if (StringUtils.isEmpty(txtSignupSum.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入签约金额!");
			txtSignupSum.setFocus();
			return false;
		}
		if (!NumberUtils.isNumber(txtSignupSum.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"签约金额输入错误，请重新输入!");
			txtSignupSum.setFocus();
			return false;
		}
		if (new BigDecimal(txtSignupSum.getText()).compareTo(new BigDecimal(0)) <= 0) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"签约金额应大于0，请重新输入!");
			txtSignupSum.setFocus();
			return false;
		}
		if (StringUtils.isEmpty(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"请输入合同号!");
			txtContractNo.setFocus();
			return false;
		}
		if (haveSpecialChar(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号只包含字母及数字，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		if (txtContractNo.getText().length() != 10) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号长度应为10，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		if (osDepartmentContractService.checkContractNoExists(txtContractNo.getText())
				|| osContractService.checkContractNoExists(txtContractNo.getText())) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"合同号重复，请重新输入!");
			txtContractNo.setFocus();
			return false;
		}
		if (!checkLicense.getSelection() && new BigDecimal(txtRemainingDeposit.getText())
				.compareTo(new BigDecimal(txtSignupSum.getText())) < 0) {
			MessageDialog.openError(getShell(), IMessageKeys.INFORMATION,
					"押金剩余金额小于签约金额，请选择特许再签约，或者修改签约金额!");
			checkLicense.setFocus();
			return false;
		}
		return true;
	}
	
	private boolean haveSpecialChar(String str) {
		for(char c : str.toCharArray()) {
			System.out.println(c);
			if (c < 48)
				return true;
			if (c > 57 && c < 65)
				return true;
			if (c > 90 && c < 97)
				return true;
			if (c > 122)
				return true;
		}
		return false;
	}
	
	public void setOsDepartmentContract(OsDepartmentContract osDepartmentContract) {
		this.osDepartmentContract = osDepartmentContract;
	}
	
	private OsDepartmentContract getOsDepartmentContract() {
		if(!checkInfo()) return null;
		
		OsDepartmentContract osDepartmentContract = new OsDepartmentContract();
		try {
			osDepartmentContract.setSignupDate(dateFormat.parse(txtSignupDate.getText()));
		} catch (ParseException e) {
			e.printStackTrace();
		}
		osDepartmentContract.setSignupSum(new BigDecimal(txtSignupSum.getText()).setScale(2, BigDecimal.ROUND_HALF_UP));
		osDepartmentContract.setContractNo(txtContractNo.getText());
		osDepartmentContract.setDepartment(new Department(departmentIds.get(comboDepartment.getSelectionIndex())));
		osDepartmentContract.setName(txtStudentName.getText());
		osDepartmentContract.setCountry(new Country(countryIds.get(comboCountry.getSelectionIndex())));
		osDepartmentContract.setLicense(checkLicense.getSelection());
		
		
		return osDepartmentContract;
	}

	/**
	 * Create contents of the button bar
	 * @param parent
	 */
	@Override
	protected void createButtonsForButtonBar(Composite parent) {
		if (readonly) {
			createButton(parent, IDialogConstants.CANCEL_ID,
					IDialogConstants.OK_LABEL, false);
		} else {
			createButton(parent, IDialogConstants.OK_ID, "签约",
					true);
			createButton(parent, IDialogConstants.CANCEL_ID,
					IDialogConstants.CANCEL_LABEL, false);
		}
	}

	/**
	 * Return the initial size of the dialog
	 */
	@Override
	protected Point getInitialSize() {
		return new Point(365, 355);
	}
	protected void configureShell(Shell newShell) {
		super.configureShell(newShell);
		newShell.setText("部门签约表");
	}
	protected void buttonPressed(int buttonId) {
		if (buttonId == IDialogConstants.OK_ID) {
			OsDepartmentContract contract = getOsDepartmentContract();
			if (contract == null) {
				return;
			}
			try {
				osDepartmentContractService.save(contract);
			} catch (Exception ex) {
				MessageDialog.openError(getShell(), IMessageKeys.FAIL, ex
						.getMessage());
			}
		}
		super.buttonPressed(buttonId);
	}

}
